package com.example.demo.resource;

import com.example.demo.dao.UserMapper;
import com.example.demo.dataobject.User;
import com.example.demo.utils.AesCbcUtil;
import com.example.demo.utils.HttpUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.aopalliance.reflect.Code;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Path("users")
public class UserResource {
    private static final  String appid = "wxb03c708922286cf4";
    private static final  String secret = "ed417ae61cbdae1dfdb9ed156d37e8f5";
    private static ObjectMapper mapper = new ObjectMapper();

    @Autowired
    UserMapper userMapper;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Map addUser(@RequestBody Map<String,String> params){

        Map<String, Object> result = new LinkedHashMap<>();

        User user = new User();
        try {
            //获取加密的openid和session_key
            Map<String,String> map = getSecretInfo(params.get("code"));

            if (map.containsKey("openid")&&map.containsKey("session_key")) {
                String openid = map.get("openid");
                String sessionKey = map.get("session_key");
                //解密，获取用户信息
                String info  = AesCbcUtil.decrypt(params.get("encryptedData"),sessionKey,params.get("iv"),"UTF-8");

                Map<String,Object> userInfo = mapper.readValue(info, Map.class);
                user.setNickname(userInfo.get("nickName").toString());
                user.setOpenid(userInfo.get("openId").toString());
                user.setAvatarurl(userInfo.get("avatarUrl").toString());
                user.setGender(Byte.valueOf(userInfo.get("gender").toString()));
                userMapper.insert(user);

                result.put("state", "ok");
                result.put("msg", "插入用户信息成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("state", "failed");
            result.put("msg","插入用户信息失败");
        }
        return result;
    }


    public Map<String,String> getSecretInfo(String code) throws IOException {
        String s  = HttpUtils.doGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code");

        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(s, Map.class);
        return map;
    }
 }
